const express = require("express");
const aiService = require("./aiService");
const {spawn} = require('child_process');
const iconv = require('iconv-lite');
const net = require('net');
const readline = require('readline');

const app = express();
const port = 3000;

const OpenAI = require("openai");

// 构造 client
const hunyuan = new OpenAI({
    apiKey: process.env['HUNYUAN_API_KEY'], // 混元 APIKey
    baseURL: "https://api.hunyuan.cloud.tencent.com/v1", // 混元 endpoint
});


app.use(express.urlencoded({extended: true, limit: "10mb"}));

app.post("/api/image-recognition", (req, res) => {
    const {base64, prompttext, userrole} = req.body;
    console.log("/api/image-recognition");
    try {
        aiService.recognizeImageContent(base64, '请直接说出图片中人脸情绪，情绪包括高兴，生气，愤怒，忧郁，平静', userrole).then((completion) => {
            console.log('image return :' + completion.choices[0].message.content);
            console.log('prompt to hunyuan:' + prompttext)
            // 自定义参数传参示例
            hunyuan.chat.completions.create({
                model: 'hunyuan-role',
                messages: [{ role: userrole, content: prompttext + completion.choices[0].message.content }],
                // @ts-expect-error key is not yet public
                enable_enhancement: true, // <- 自定义参数
            }).then((completion) => {
                console.log('hunyuan: ' + completion.choices[0]?.message?.content);
                res.send({
                    msg: completion.choices[0].message.content,
                });
            });
        });
    } catch (e) {
        res.send({
            msg: e,
        });
    }
});

app.post("/api/text-recognition", (req, res) => {
    const {base64, prompttext, userrole} = req.body;
    console.log("/api/text-recognition");
    try {
        aiService.recognizeTextContent(base64, prompttext, userrole).then((completion) => {
            console.log(completion);
            res.send({
                msg: completion,
            });
        });
    } catch (e) {
        res.send({
            msg: e,
        });
    }
});


app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});
